<?php
/**
 * User: zoudingyong <sheyingtg@qq.com>
 * Date: 2019-10-09 16:20
 */

namespace app\api\controller;

use classes\Oss;
use QCloud\COSSTS\Sts;
use ShaoZeMing\AliSTS\Services\STSService;
use think\Db;
use think\facade\Cache;

class Com extends Base
{

    public $region = 'tp_region';

    /**
     * 上传图片
     * @return array
     * @throws \think\exception\DbException
     */
    public function upload()
    {
        $file = $this->request->file('file');
        if (empty($file)) {
            return $this->renderError('请选择图片再上传');
        }
        $result = upload_by_local($file);

        if ($result) {
            return $this->renderSuccess('上传成功', $result['url']);
        } else {
            return $this->renderError('上传失败');
        }
    }

    //发送短信验证码
    public function send_code()
    {
        $mobile = $this->_data['mobile'];
        if (!check_mobile_number($mobile)) {
            return $this->renderError('手机号不正确');
        }
        $code = createPhoneCode(6);
        $msg = '验证码：' . $code . '，工作人员不会索取，请勿泄露!';
        $send_record = Cache::get('send_mobile:' . $mobile);
        if ($send_record) {
            return $this->renderError('请求过于频繁，请稍后再试');
        }
        $result = send_sms_to_zz($mobile, $msg);
        if ($result) {
            Cache::set('mobile:' . $mobile, $code, 600); //验证码
            Cache::set('send_mobile:' . $mobile, $code, 60); //再次发送短信间隔时间
            return $this->renderSuccess('发送成功');
        } else {
            return $this->renderError('发送失败');
        }

    }

    //获取省份
    public function get_province()
    {
        $list = Db::name($this->region)
            ->field('id province_id,name')
            ->where('parent_id', 0)
            ->order('sort desc')
//            ->cache('get_province', 3600 * 24)
            ->select();

        return $this->renderSuccess('省份列表', $list);
    }

    //根据省份id获取城市
    public function get_city()
    {
        $province_id = $this->_data['province_id'];
        $list = Db::name($this->region)
            ->field('id city_id,name')
            ->where('parent_id', $province_id)
            ->order('sort desc')
//            ->cache('get_city' . $province_id, 3600 * 24)
            ->select();

        return $this->renderSuccess('城市列表', $list);
    }

    //根城市id获取城区
    public function get_district()
    {
        $city_id = $this->_data['city_id'];
        $list = Db::name($this->region)
            ->field('id district_id,name')
            ->where('parent_id', $city_id)
            ->order('sort desc')
//            ->cache('get_district' . $city_id, 3600 * 24)
            ->select();
        return $this->renderSuccess('城区列表', $list);
    }

    /**
     * oss鉴权
     * @return array
     */
    public function oss()
    {
        $type = $this->_data['type']; //0 图片 1视频
        if ($type) {
            $object = 'video/' . md5(time()) . '.mp4';
        } else {
            $object = 'image/' . md5(time()) . '.jpg';
        }

        $result = Oss::signedUrl($object);
        return $this->renderSuccess('oss鉴权', $result);
    }

    /**
     * oss鉴权
     * https://github.com/ShaoZeMing/Aliyun-Sts
     * https://help.aliyun.com/document_detail/31920.html
     * https://blog.csdn.net/yangkangv/article/details/97688518
     * JS通过STS访问阿里云OSS https://blog.csdn.net/yangkangv/article/details/97688518
     * 网页版上传视频报错 解决方案 https://www.ffeeii.com/2248.html
     * @return array
     */
    public function sts()
    {

        /*STS配置*/

        $config = [
            'sts' =>
                [
                    'AccessKeyID' => 'LTAI5tMr5UXR3VSEfpfDQGXx',
                    'AccessKeySecret' => 'aEn86ARwnPZPvFzLRTYrEWsZTcJLyT',
                    'regionId' => 'cn-shenzhen',
                    'endpoint' => 'sts.cn-shenzhen.aliyuncs.com',
                    'roleArn' => 'acs:ram::1387304248889889:role/aliyunosstokengeneratorrole',  // 角色资源描述符，在RAM的控制台的资源详情页上可以获取
                    'timeout' => '3600',  // 令牌过期时间
                    'client_name' => 'external-username',  // setRoleSessionName可以不改
                    // 在扮演角色(AssumeRole)时，可以附加一个授权策略，进一步限制角色的权限；
                    // 详情请参考《RAM使用指南》
                    // 这代表所有权限
                    'policy' => [
                        'Statement' => [
                            [
                                'Action' => ["oss:*"],
                                'Effect' => 'Allow',
                                'Resource' => ["acs:oss:*:*:*"],
                            ]
                        ]
                    ]
                ]];

        try {
            $sts = new STSService($config);
            $result = $sts->getToken(); // 获取权限参数
            $result = $this->_render($result);
            return $this->renderSuccess('oss鉴权', $result);
        } catch (\Exception $e) {
            $err = "Error : 错误：" . $e->getMessage();
            return $this->renderError('错误', $err);
        }


    }

    private function _render($res)
    {
        $data = json_encode($res);
        $res = json_decode($data, true);
        if (empty($res['Credentials'])) {
            return [];
        } else {
            return [
                'accessKeySecret' => $res['Credentials']['AccessKeySecret'] ?: '',
                'accessKeyId' => $res['Credentials']['AccessKeyId'] ?: '',
                'expiration' => $res['Credentials']['Expiration'] ?: '',
                'securityToken' => $res['Credentials']['SecurityToken'] ?: '',
                'Bucket' => 'hapgolfqz',
                'Endpoint' => 'oss-cn-shenzhen.aliyuncs.com',
            ];
        }
    }

    public function cos_sts()
    {
        $sts = new Sts();
        $c = config("TencentCloud");// 这里是我的config文件，此处根据你的代码修改
        $config = array(
            'url' => 'https://sts.tencentcloudapi.com/',
            'domain' => 'sts.tencentcloudapi.com',
            'secretId' => $c['SecretId'],
            'secretKey' => $c['SecretKey'],
            'bucket' => $c['bucket'],
            'region' => $c['region'],
            'durationSeconds' => 7200, //过期时间 秒 最大7200
            'allowPrefix' => '*', // 全部权限
            'allowActions' => array(// 简单上传
                'name/cos:PutObject',
                'name/cos:PostObject', // 分片上传
                'name/cos:InitiateMultipartUpload',
                'name/cos:ListMultipartUploads',
                'name/cos:ListParts',
                'name/cos:UploadPart',
                'name/cos:CompleteMultipartUpload'
            )

        );

        // 获取临时密钥，计算签名
        $tempKeys = $sts->getTempKeys($config);
        return $this->renderSuccess('cos鉴权', $tempKeys);

    }

}